package com.haixiaoke.saas.apartment.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.haixiaoke.saas.apartment.domain.*;
import com.haixiaoke.saas.apartment.mapper.HousingAllocationMapper;
import com.haixiaoke.saas.apartment.service.*;
import com.haixiaoke.saas.common.constant.HouseConstants;
import com.haixiaoke.saas.common.core.domain.AjaxResult;
import com.haixiaoke.saas.common.core.domain.entity.SysDictData;
import com.haixiaoke.saas.common.exception.ServiceException;
import com.haixiaoke.saas.common.tenant.TenantContext;
import com.haixiaoke.saas.common.utils.DateUtils;
import com.haixiaoke.saas.common.utils.GsonUtil;
import com.haixiaoke.saas.house.domain.Estate;
import com.haixiaoke.saas.house.domain.House;
import com.haixiaoke.saas.house.service.IEstateService;
import com.haixiaoke.saas.house.service.IHotAttractionsService;
import com.haixiaoke.saas.house.service.IHouseService;
import com.haixiaoke.saas.order.domain.ConfirmationVO;
import com.haixiaoke.saas.order.domain.OrderHousingExpenses;
import com.haixiaoke.saas.order.service.IOrderService;
import com.haixiaoke.saas.system.domain.SysArea;
import com.haixiaoke.saas.system.service.ISysDictDataService;
import com.haixiaoke.saas.system.service.ISysDictTypeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 房屋配置Service业务层处理
 *
 * @author panda
 * @date 2024-03-21
 */
@Service
public class HousingAllocationServiceImpl implements IHousingAllocationService {
    @Autowired
    private HousingAllocationMapper housingAllocationMapper;
    @Autowired
    private IHouseService houseService;
    @Autowired
    private IApartmentLabelService iApartmentLabelService;
    @Autowired
    private IHotAttractionsService iHotAttractionsService;
    @Autowired
    private IHouseRequireService iHouseRequireService;
    @Autowired
    private IHousingPriceService housingPriceService;
    @Autowired
    private ISysDictDataService sysDictDataService;
    @Autowired
    private IServiceFacilitiesService serviceFacilitiesService;
    @Autowired
    private ICalendarPriceService calendarPriceService;
    @Autowired
    private IUnsubscribeRuleService unsubscribeRuleService;
    @Autowired
    private IEstateService estateService;
    @Autowired
    private IOrderService orderService;
    @Autowired
    private IHouseRequireService houseRequireService;
    @Autowired
    private ISysDictTypeService dictTypeService;

    /**
     * 查询房屋配置
     *
     * @param houseId 房屋主键
     * @return 房屋配置
     */
    @Override
    public HousingAllocation selectHousingAllocationByAllocationId(String houseId) {
        House house = houseService.selectHouseById(houseId);
        HousingAllocation allocation = housingAllocationMapper.selectHousingAllocationByHouseId(houseId);
        if (ObjectUtil.isEmpty(allocation)) {
            HousingAllocation housingAllocation = new HousingAllocation();
            housingAllocation.setHouse(house);
            return housingAllocation;
        }

        //设施id处理
        if (StrUtil.isNotBlank(allocation.getFacilitiesIds())) {
            List<String> split = StrUtil.split(allocation.getFacilitiesIds(), ',');
            allocation.setFacilitiesIdList(split.stream().map(Long::valueOf).collect(Collectors.toList()));
        }
        // 景区id处理
        String attractionsIds = allocation.getAttractionsIds();
        if (StrUtil.isNotBlank(attractionsIds)) {
            List<String> split = StrUtil.split(attractionsIds, ',');
            allocation.setAttractionsIdList(split.stream().map(Long::valueOf).collect(Collectors.toList()));
        }
        //标签数据处理
        String labelIds = allocation.getLabelIds();
        if (StrUtil.isNotBlank(labelIds)) {
            List<String> split = StrUtil.split(labelIds, ',');
            allocation.setLabelIdList(split.stream().map(Long::valueOf).collect(Collectors.toList()));
        }
        String checkInType = allocation.getCheckInType();
        if (StrUtil.isNotBlank(checkInType)) {
            List<String> split = StrUtil.split(checkInType, ',');
            allocation.setCheckInTypeList(split);
        }
        List<HouseRequire> requireList = iHouseRequireService.selectHouseRequireByHouseId(houseId);
        allocation.setHouseRequireList(requireList);
        List<HousingPrice> housingPriceList = housingPriceService.selectHousingPriceByAllocationId(allocation.getAllocationId());
        allocation.setHousingPriceList(housingPriceList);
        allocation.setHouse(house);
        allocation.setApartmentPictureList(StrUtil.split(allocation.getApartmentPicture(), ','));
        allocation.setCheckInTypeList(StrUtil.split(allocation.getCheckInType(), ','));
        return allocation;
    }

    /**
     * 查询房屋配置列表
     *
     * @param housingAllocation 房屋配置
     * @return 房屋配置
     */
    @Override
    public List<HousingAllocation> selectHousingAllocationList(HousingAllocation housingAllocation) {
        return housingAllocationMapper.selectHousingAllocationList(housingAllocation);
    }

    /**
     * 新增房屋配置
     *
     * @param housingAllocation 房屋配置
     * @return 结果
     */
    @Override
    @Transactional
    public int insertHousingAllocation(HousingAllocation housingAllocation) {
        Date nowDate = DateUtils.getNowDate();
        //图片数据封装
        housingAllocation.setApartmentPicture(StringUtils.join(housingAllocation.getApartmentPictureList(), ","));
        housingAllocation.setCheckInType(StringUtils.join(housingAllocation.getCheckInTypeList(), ","));
        /*if (CollectionUtil.isNotEmpty(housingAllocation.getInspectionPictureList())) {
            housingAllocation.setInspectionPicture(StringUtils.join(housingAllocation.getInspectionPictureList(), ","));
        }*/

        //设施数据封装
        if (CollectionUtil.isNotEmpty(housingAllocation.getFacilitiesIdList())) {
            housingAllocation.setFacilitiesIds(StringUtils.join(housingAllocation.getFacilitiesIdList(), ","));
        }
        //标签数据封装
        if (CollectionUtil.isNotEmpty(housingAllocation.getLabelIdList())) {
            housingAllocation.setLabelIds(StringUtils.join(housingAllocation.getLabelIdList(), ","));
            housingAllocation.setLabelNames(iApartmentLabelService.selectApartmentLabelNamesByLabelIdIn(housingAllocation.getLabelIdList()));
        }
        //景区数据封装
        if (CollectionUtil.isNotEmpty(housingAllocation.getAttractionsIdList())) {
            housingAllocation.setAttractionsFullNames(iHotAttractionsService.selectHotAttractionFullNamesByIdIn(housingAllocation.getAttractionsIdList()));
            housingAllocation.setAttractionsIds(StringUtils.join(housingAllocation.getAttractionsIdList(), ","));
        }
        housingAllocation.setCreateTime(nowDate);
        int result = housingAllocationMapper.insertHousingAllocation(housingAllocation);
        if (result > 0) {
            if (CollectionUtil.isNotEmpty(housingAllocation.getHouseRequireList())) {
                for (HouseRequire houseRequire : housingAllocation.getHouseRequireList()) {
                    houseRequire.setCreateTime(nowDate);
                    houseRequire.setCreateBy(housingAllocation.getCreateBy());
                    houseRequire.setTenantId(housingAllocation.getTenantId());
                    houseRequire.setAllocationId(housingAllocation.getAllocationId());
                    houseRequire.setHouseId(housingAllocation.getHouseId());
                }
                //房间要求数据
                iHouseRequireService.insertBatchHouseRequire(housingAllocation.getHouseRequireList());
                //房价数据
                housingAllocation.getHousingPriceList().forEach(x -> {
                    x.setAllocationId(housingAllocation.getAllocationId());
                    x.setHouseId(housingAllocation.getHouseId());
                });
                housingPriceService.insertBatchHousingPrice(housingAllocation.getHousingPriceList());
            }
        }
        return result;
    }

    /**
     * 修改房屋配置
     *
     * @param housingAllocation 房屋配置
     * @return 结果
     */
    @Override
    @Transactional
    public int updateHousingAllocation(HousingAllocation housingAllocation) {
        HousingAllocation byAllocationId = housingAllocationMapper.selectHousingAllocationByAllocationId(housingAllocation.getAllocationId());
        if (!TenantContext.getTenantId().equals(byAllocationId.getTenantId())) {
            throw new ServiceException("操作的数据不为当前租户的数据");
        }
        //图片数据封装
        housingAllocation.setApartmentPicture(StringUtils.join(housingAllocation.getApartmentPictureList(), ","));
        housingAllocation.setCheckInType(StringUtils.join(housingAllocation.getCheckInTypeList(), ","));
        // 房屋设施数据处理
        if (CollectionUtil.isNotEmpty(housingAllocation.getFacilitiesIdList())) {
            housingAllocation.setFacilitiesIds(StringUtils.join(housingAllocation.getFacilitiesIdList(), ","));
        }

        List<Long> attractionsIds = housingAllocation.getAttractionsIdList();
        // 热门景点全名
        if (CollectionUtil.isNotEmpty(attractionsIds)) {
            housingAllocation.setAttractionsFullNames(iHotAttractionsService.selectHotAttractionFullNamesByIdIn(attractionsIds));
            housingAllocation.setAttractionsIds(StringUtils.join(attractionsIds, ","));
        }


        List<Long> labelIds = housingAllocation.getLabelIdList();
        // 房屋标签
        if (CollectionUtil.isNotEmpty(labelIds)) {
            housingAllocation.setLabelNames(iApartmentLabelService.selectApartmentLabelNamesByLabelIdIn(labelIds));
            housingAllocation.setLabelIds(StringUtils.join(labelIds, ","));
        }
        Date nowDate = DateUtils.getNowDate();
        if (CollectionUtil.isNotEmpty(housingAllocation.getHouseRequireList())) {
            for (HouseRequire houseRequire : housingAllocation.getHouseRequireList()) {
                houseRequire.setUpdateTime(nowDate);
                houseRequire.setUpdateBy(housingAllocation.getUpdateBy());
            }
            iHouseRequireService.updateBatchHouseRequire(housingAllocation.getHouseRequireList());
        }
        if (CollectionUtil.isNotEmpty(housingAllocation.getHousingPriceList())) {
            housingPriceService.updateBatchHousingPrice(housingAllocation.getHousingPriceList());
        }
        housingAllocation.setUpdateTime(nowDate);
        return housingAllocationMapper.updateHousingAllocation(housingAllocation);
    }

    /**
     * 批量删除房屋配置
     *
     * @param allocationIds 需要删除的房屋配置主键
     * @return 结果
     */
    @Override
    public int deleteHousingAllocationByAllocationIds(Long[] allocationIds) {
        return housingAllocationMapper.deleteHousingAllocationByAllocationIds(allocationIds);
    }

    /**
     * 删除房屋配置信息
     *
     * @param allocationId 房屋配置主键
     * @return 结果
     */
    @Override
    public int deleteHousingAllocationByAllocationId(Long allocationId) {
        return housingAllocationMapper.deleteHousingAllocationByAllocationId(allocationId);
    }

    /**
     * 根据房屋id查询房屋配置
     *
     * @param houseId 房屋id
     * @return
     */
    @Override
    public HousingAllocation selectHousingAllocationByHouseId(String houseId) {
        return housingAllocationMapper.selectHousingAllocationByHouseId(houseId);
    }

    @Override
    public int softDeleteHousingAllocationByAllocationId(Long allocationId) {
        return housingAllocationMapper.softDeleteHousingAllocationByAllocationId(allocationId);
    }

    @Override
    public Boolean checkAllocationByHouse(String houseId) {
        int result = housingAllocationMapper.checkAllocationByHouse(houseId);
        return result > 0;
    }

    @Override
    public List<Map<String, Object>> countByState(String tenantId) {
        List<Map<String, Object>> list = new ArrayList<>();
        int houseAll = houseService.countHouseAll(tenantId);
        int apartmentStateUp = housingAllocationMapper.countByState(1, tenantId);
        int apartmentStateDown = housingAllocationMapper.countByState(2, tenantId);
        int allocationStateNo = housingAllocationMapper.countByState(3, tenantId);
        Map<String, Object> houseMap = new HashMap<>();
        houseMap.put("value", "");
        houseMap.put("label", "全部");
        houseMap.put("type", "");
        houseMap.put("number", houseAll);

        Map<String, Object> upMap = new HashMap<>();
        upMap.put("value", "0");
        upMap.put("label", "已上架");
        upMap.put("type", "apartmentState");
        upMap.put("number", apartmentStateUp);

        Map<String, Object> downMap = new HashMap<>();
        downMap.put("value", "1");
        downMap.put("label", "已下架");
        downMap.put("type", "apartmentState");
        downMap.put("number", apartmentStateDown);

        Map<String, Object> noMap = new HashMap<>();
        noMap.put("value", "1");
        noMap.put("label", "未配置");
        noMap.put("type", "allocationState");
        noMap.put("number", allocationStateNo);

        list.add(houseMap);
        list.add(upMap);
        list.add(downMap);
        list.add(noMap);
        return list;
    }

    /**
     * 修改房屋配置的上下架状态
     */
    @Override
    public int updateHousingAllocationState(HousingAllocation housingAllocation) {
        HousingAllocation allocation = housingAllocationMapper.selectHousingAllocationByAllocationId(housingAllocation.getAllocationId());
        if (ObjectUtil.isNotEmpty(allocation)) {
            if (HouseConstants.APARTMENT_STATE_UP.equals(allocation.getApartmentState())) {
                allocation.setApartmentState(HouseConstants.APARTMENT_STATE_DOWN);
            } else if (HouseConstants.APARTMENT_STATE_DOWN.equals(allocation.getApartmentState())) {
                allocation.setApartmentState(HouseConstants.APARTMENT_STATE_UP);
            }
            return housingAllocationMapper.updateHousingAllocationState(allocation);
        }
        return 0;
    }

    /**
     * 价格日历列表查询房屋信息
     *
     * @param allocation
     * @return
     */
    @Override
    public List<HousingAllocation> selectCalendarPriceListByAllocation(HousingAllocation allocation) {
        return housingAllocationMapper.selectCalendarPriceListByAllocation(allocation);
    }

    @Override
    public Map<String, Map<String, Object>> selectAllocationIdAndHouseId(String[] houseIds) {
        return housingAllocationMapper.selectAllocationIdAndHouseId(houseIds);
    }

    @Override
    public List<HousingAllocation> selectHousingAllocationHomePage(HousingAllocation housingAllocation) {
        //封装今天是星期几
        housingAllocation.setWeek(String.valueOf(LocalDate.now().getDayOfWeek().getValue()));
        List<HousingAllocation> housingAllocationHomePage = housingAllocationMapper.selectHousingAllocationHomePage(housingAllocation);
        List<SysDictData> allocationType = dictTypeService.selectDictDataByType("allocation_type");
        Map<String, String> typeMapping = new LinkedHashMap<>();
        allocationType.forEach(dictData -> {
            typeMapping.put(dictData.getDictValue(), dictData.getDictLabel());
        });

        for (HousingAllocation allocation : housingAllocationHomePage) {
            String houseType = typeMapping.get(allocation.getAllocationType());
            // String roomType = sysDictDataService.selectDictLabel("dict_room_type", allocation.getHouse().getRoomType());
            String roomType = allocation.getHouse().getRoomType();
            allocation.setTitle(houseType + allocation.getHouse().getHouseArea() + "m²·" + roomType + "室" + allocation.getBedNumber() + "床·" + "可住" + allocation.getCheckInNumber() + "人");
            allocation.setApartmentPictureList(StrUtil.split(allocation.getApartmentPicture(), ','));
        }
        return housingAllocationHomePage;
    }

    @Override
    public List<HousingAllocation> selectHousingAllocationHomePageList(HousingAllocation housingAllocation) {
        //封装今天是星期几
        housingAllocation.setWeek(String.valueOf(LocalDate.now().getDayOfWeek().getValue()));
        List<SysDictData> allocationType = dictTypeService.selectDictDataByType("allocation_type");
        Map<String, String> typeMapping = new LinkedHashMap<>();
        allocationType.forEach(dictData -> {
            typeMapping.put(dictData.getDictValue(), dictData.getDictLabel());
        });

        List<HousingAllocation> housingAllocationHomePage = housingAllocationMapper.selectHousingAllocationHomePageList(housingAllocation);
        for (HousingAllocation allocation : housingAllocationHomePage) {
            String houseType = typeMapping.get(allocation.getAllocationType());

            // String roomType = sysDictDataService.selectDictLabel("dict_room_type", allocation.getHouse().getRoomType());
            String roomType = allocation.getHouse().getRoomType();
            allocation.setTitle(houseType + allocation.getHouse().getHouseArea() + "m²·" + roomType + "室" + allocation.getBedNumber() + "床·" + "可住" + allocation.getCheckInNumber() + "人");
            allocation.setApartmentPictureList(StrUtil.split(allocation.getApartmentPicture(), ','));
        }
        return housingAllocationHomePage;
    }
    @Override
    public HousingAllocation flatSelectHousingAllocationByHouseId(HousingAllocation allocation) {
        HousingAllocation housingAllocation = housingAllocationMapper.flatSelectHousingAllocationByHouseId(allocation.getHouseId());
        if (StrUtil.isBlank(housingAllocation.getFacilitiesIds())) {
            housingAllocation.setWindowState("1");
            housingAllocation.setElevatorState("1");
        } else {
            List<String> split = StrUtil.split(housingAllocation.getFacilitiesIds(), ',');
            List<ServiceFacilities> serviceFacilitiesList = serviceFacilitiesService.selectBatchHouseFacilitiesByFacilitiesId(split.stream().map(Long::valueOf).collect(Collectors.toList()));
            if (CollectionUtil.isNotEmpty(serviceFacilitiesList)) {
                // 使用流API检查字段是否包含指定字符串
                boolean windowState = serviceFacilitiesList.stream()
                        .map(ServiceFacilities::getFacilitiesName) // 获取字段值
                        .anyMatch(fieldValue -> fieldValue.contains("窗户"));
                housingAllocation.setWindowState(windowState? "0" : "1");

                boolean elevatorState = serviceFacilitiesList.stream()
                        .map(ServiceFacilities::getFacilitiesName) // 获取字段值
                        .anyMatch(fieldValue -> fieldValue.contains("电梯"));
                housingAllocation.setElevatorState(elevatorState? "0" : "1");
            } else {
                housingAllocation.setWindowState("1");
                housingAllocation.setElevatorState("1");
            }

            List<SysDictData> dict = dictTypeService.selectDictDataByType("facilities_type");
            if (CollUtil.isNotEmpty(dict)) {

                // 封装服务设施
                Map<String, List<ServiceFacilities>> map = new LinkedHashMap<>();
                Map<String, String> typeMapping = new LinkedHashMap<>();

                dict.forEach(dictData -> {
                    typeMapping.put(dictData.getDictValue(), dictData.getDictLabel());
                });

                for (String type : typeMapping.values()) {
                    map.put(type, new ArrayList<>());
                }

                for (ServiceFacilities facilities : serviceFacilitiesList) {
                    String category = typeMapping.get(facilities.getFacilitiesType());
                    if (StrUtil.isNotBlank(category)) {
                        map.get(category).add(facilities);
                    }
                }
                Map<String, List<ServiceFacilities>> stringListLinkedHashMap = new LinkedHashMap<>();
                for (String s : map.keySet()) {
                    List<ServiceFacilities> serviceFacilities = map.get(s);
                    if (CollectionUtil.isNotEmpty(serviceFacilities)) {
                        stringListLinkedHashMap.put(s, serviceFacilities);
                    }
                }

                housingAllocation.setServiceFacilitiesMap(stringListLinkedHashMap);
            }

            // housingAllocation.setServiceFacilitiesList(serviceFacilitiesList);
        }
        // 房间要求
        List<HouseRequire> houseRequires = houseRequireService.selectHouseRequireByHouseId(housingAllocation.getHouseId());
        housingAllocation.setHouseRequireList(houseRequires);

        // 查询退订退则
        UnsubscribeRule unsubscribeRule = unsubscribeRuleService.selectUnsubscribeRuleById(housingAllocation.getUnsubscribeRuleId());
        if (!HouseConstants.UNSUBSCRIBE_TYPE_STRICT.equals(unsubscribeRule.getUnsubscribeType())) {
            Map<String, BigDecimal> map = GsonUtil.toMap(unsubscribeRule.getUnsubscribeContent());
            unsubscribeRule.setUnsubscribeContentMap(map);
        }

        // 查询经纬度
        House house = housingAllocation.getHouse();
        if (ObjectUtil.isNotNull(house)) {
            Estate estate = estateService.selectEstateByEstateId(house.getEstateId());
            housingAllocation.setLatitude(estate.getLatitude());
            housingAllocation.setLongitude(estate.getLongitude());
        }

        housingAllocation.setUnsubscribeRule(unsubscribeRule);
        housingAllocation.setApartmentPictureList(StrUtil.split(housingAllocation.getApartmentPicture(), ','));
        housingAllocation.setCheckInTypeList(StrUtil.split(housingAllocation.getCheckInType(), ','));
        housingAllocationMapper.addBrowseNum(housingAllocation.getAllocationId());

        String allocationType = sysDictDataService.selectDictLabel("allocation_type", housingAllocation.getAllocationType());
        String roomType = housingAllocation.getHouse().getRoomType();
        housingAllocation.setTitle(allocationType + housingAllocation.getHouse().getHouseArea() + "m²·" + roomType + "室" + housingAllocation.getBedNumber() + "床·" + "可住" + housingAllocation.getCheckInNumber() + "人");
        return housingAllocation;
    }

    @Override
    public List<HousingAllocation> selectHouseByAllocation(House house) {
        return housingAllocationMapper.selectHouseByAllocation(house);
    }

    @Override
    public HousingAllocation flatestimatedAmount(HousingAllocation allocation) {
        List<HousingPrice> housingPriceList = housingPriceService.selectHousingPriceByHouseId(allocation.getHouseId());
        //查询价格日历
        List<CalendarPrice> calendarPriceList = calendarPriceService.selectCalendarPriceListByTime(null, allocation.getHouseId(), allocation.getStartTime(), allocation.getEndTime(), false);
        //日历价格，key为时间
        Map<LocalDate, CalendarPrice> calendarPriceMap = calendarPriceList.stream().collect(Collectors.toMap(CalendarPrice::getCalendarTime, x -> x));
        //日历价格，key为星期1~7
        Map<String, HousingPrice> housingPriceMap = housingPriceList.stream().collect(Collectors.toMap(HousingPrice::getWeek, x -> x));
        //遍历时间，统计金额
        LocalDate start = allocation.getStartTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();// 起始日期
        LocalDate end = allocation.getEndTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();// 结束日期
        long between = DateUtil.between(allocation.getStartTime(), allocation.getEndTime(), DateUnit.DAY, false);//相隔时间
        BigDecimal totalPrice = BigDecimal.ZERO;
        while (start.isBefore(end)) {
            CalendarPrice calendarPrice = calendarPriceMap.get(start);
            if (ObjectUtil.isEmpty(calendarPrice)) {
                HousingPrice housingPrice = housingPriceMap.get(String.valueOf(start.getDayOfWeek().getValue()));
                totalPrice = totalPrice.add(housingPrice.getHousePrice());
            } else {
                totalPrice = totalPrice.add(calendarPrice.getCalendarPrice());
            }
            start = start.plusDays(1); // 增加一天
        }
        HousingAllocation housingAllocation = new HousingAllocation();
        housingAllocation.setTotalPrice(totalPrice);
        //保留两位小数，向上取数
        housingAllocation.setAveragePrice(totalPrice.divide(BigDecimal.valueOf(between), 2, RoundingMode.HALF_UP));
        return housingAllocation;
    }

    @Override
    public boolean checkTimeRange(String houseId, Date endTime) {
        HousingAllocation allocation = this.selectHousingAllocationByHouseId(houseId);
        LocalDate end = endTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        int months = 0;
        switch (allocation.getLeaseScope()) {
            case HouseConstants.LEASE_SCOPE_THREE_MONTHS:
                months = 3;
                break;
            case HouseConstants.LEASE_SCOPE_SIX_MONTHS:
                months = 6;
                break;
            case HouseConstants.LEASE_SCOPE_YEAR:
                months = 12;
                break;
            case HouseConstants.LEASE_SCOPE_TWO_YEARS:
                months = 24;
                break;
        }
        //当前时间的最大范围时间相加后，是否在结束时间之前，true则超出时间范围，false则相反(相加后的时间和结束时间不能相等)
        return !LocalDate.now().plusMonths(months).isAfter(end);
    }

    @Override
    public List<HousingAllocation> selectAllocationByHouseIds(List<String> houseIds) {
        return housingAllocationMapper.selectAllocationByHouseIds(houseIds);
    }

    @Override
    public List<Map<String, Object>> unsubscribeAmount(HousingAllocation allocation) {
        HousingAllocation housingAllocation = housingAllocationMapper.selectHousingAllocationByHouseId(allocation.getHouseId());
        List<HousingPrice> housingPriceList = housingPriceService.selectHousingPriceByHouseId(allocation.getHouseId());
        if (ObjectUtil.isEmpty(housingAllocation) || CollectionUtil.isEmpty(housingPriceList)) {
            throw new ServiceException("房屋数据异常，请联系房管员!");
        }
        UnsubscribeRule unsubscribeRule = unsubscribeRuleService.selectUnsubscribeRuleById(housingAllocation.getUnsubscribeRuleId());

        //当前时间年月日
        LocalDate nowDate = LocalDate.now();
        //当前时间时分秒
        LocalTime nowTime = LocalTime.now();
        //当前时间年月日时分秒
        LocalDateTime nowDateTime = LocalDateTime.now();
        ZonedDateTime startZonedDateTime = allocation.getStartTime().toInstant().atZone(ZoneId.systemDefault());
        ZonedDateTime endZonedDateTime = allocation.getEndTime().toInstant().atZone(ZoneId.systemDefault());
        LocalDate startDate = startZonedDateTime.toLocalDate();// 起始日期
        LocalDate endDate = endZonedDateTime.toLocalDate();// 结束日期
        DateTimeFormatter format = DateTimeFormatter.ofPattern("M月dd日");
        List<Map<String, Object>> list = new ArrayList<>();
        if (StrUtil.equals(HouseConstants.UNSUBSCRIBE_TYPE_STRICT, unsubscribeRule.getUnsubscribeType())) {
            LocalDateTime startDateTime = startZonedDateTime.toLocalDateTime();
            //获得开始时间的前一天的中午12点
            LocalDateTime localDateTime = startDateTime.withDayOfYear(startDateTime.getDayOfYear() - 1).withHour(12).withMinute(0).withSecond(0).withNano(0);
            String formatStr = format.format(localDateTime);
            //前一天是否在当前时间之后
            Map<String, Object> oneMap = new HashMap<>();
            if (localDateTime.isAfter(nowDateTime)) {
                oneMap.put("title", formatStr + "12:00前");
            } else {
                oneMap.put("title", "预订成功后30分钟内");
            }
            oneMap.put("value", "免费");

            Map<String, Object> twoMap = new HashMap<>();
            twoMap.put("title", formatStr + "12:00后或已入住");
            twoMap.put("value", "不可取消，扣除全部房费");
            list.add(oneMap);
            list.add(twoMap);
        } else if (StrUtil.equals(HouseConstants.UNSUBSCRIBE_TYPE_HOTEL, unsubscribeRule.getUnsubscribeType())) {
            LocalTime twelveTime = LocalTime.of(12, 0);//12点
            LocalTime eighteenTime = LocalTime.of(18, 0);//18点
            String startDateStr = format.format(startDate);
            Map<String, Object> oneMap = new HashMap<>();
            //开始时间是否在当前时间之后
            if (startDate.isAfter(nowDate)) {
                oneMap.put("title", startDateStr + "00:00前");
            } else {
                oneMap.put("title", "预订成功后30分钟内");
            }
            oneMap.put("value", "免费");
            list.add(oneMap);
            Map<String, Double> unsubscribeContentMap = GsonUtil.toMap(unsubscribeRule.getUnsubscribeContent());

            ConfirmationVO compute = orderService.compute(allocation.getStartTime(), allocation.getEndTime(), null, null, housingAllocation, housingPriceList, true, null);
//            BigDecimal totalPrice = compute.getTotalPrice()
            //获取第一天房费
            BigDecimal startPrice = compute.getOrderHousingExpensesList().stream().filter(x -> x.getRentingTime().equals(startDate))
                    .map(OrderHousingExpenses::getRentingExpenses).findFirst().orElse(BigDecimal.ZERO);

            //开始时间等于当前年月日时间，而且当前时分秒在12点之前
            if (nowTime.isBefore(twelveTime)) {
                BigDecimal discount = BigDecimal.valueOf(unsubscribeContentMap.get("1")).divide(BigDecimal.valueOf(100)).setScale(4, BigDecimal.ROUND_HALF_UP);
                Map<String, Object> twelveMap = new HashMap<>();
                twelveMap.put("title", startDateStr + "12:00前");
                twelveMap.put("value", "￥" + startPrice.multiply(discount).doubleValue());
                list.add(twelveMap);
            }

            //开始时间等于当前年月日时间，而且当前时分秒在18点之前
            if (nowTime.isBefore(eighteenTime)) {
                BigDecimal discount = BigDecimal.valueOf(unsubscribeContentMap.get("2")).divide(BigDecimal.valueOf(100)).setScale(4, BigDecimal.ROUND_HALF_UP);
                Map<String, Object> twelveMap = new HashMap<>();
                twelveMap.put("title", startDateStr + "18:00前");
                twelveMap.put("value", "￥" + startPrice.multiply(discount).doubleValue());
                list.add(twelveMap);
            }

            Map<String, Object> twoMap = new HashMap<>();
            twoMap.put("title", startDateStr + "18:00后或已入住");
            if (ChronoUnit.DAYS.between(startDate, endDate) == 1) {
                twoMap.put("value", "不可取消");
            } else {
                //每日房费价格
                BigDecimal minValue = compute.getOrderHousingExpensesList().stream()
                        .map(OrderHousingExpenses::getRentingExpenses)
                        .min(BigDecimal::compareTo).orElse(BigDecimal.ZERO);
                BigDecimal discount = BigDecimal.valueOf(unsubscribeContentMap.get("3")).divide(BigDecimal.valueOf(100)).setScale(4, BigDecimal.ROUND_HALF_UP);
                twoMap.put("value", "不可取消，未入住日期退订费￥" + minValue.multiply(discount).doubleValue() + "起");
            }
            list.add(twoMap);
        }

        return list;
    }

    @Override
    public List<SysArea> selectHousingAllocationArea() {
        return housingAllocationMapper.selectHousingAllocationArea();
    }
}
